package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.utils.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author zzyl
 * @date 2024-12-05
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;


    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //1.根据老人身份证号查询老人表看是否有该老人
        //1.1构建查询条件
        LambdaQueryWrapper<Elder> queryWrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        Elder elderOld = elderMapper.selectOne(queryWrapper);
        if (elderOld != null) {
            //1.2说明在数据库中查到了老人
            if (elderOld.getStatus() != 1) {
                //说明老人不是入住状态,进行修改操作
            } else {
                //说明老人已经存在(入住),不能重复添加了
                throw new RuntimeException("老人已经入住,不能重复入住!");
            }
        } else {
            //1.3说明在数据库中没查到老人
            //编写新增老人代码
            //3.需要更新老人占用床位的状态
            Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
            bed.setBedStatus(1);
            bedMapper.updateById(bed);
            //4.新增老人表(需要构建老人表中包含的字段)
            Elder elder = insertelder(dto, bed);
            //5.新增入住表和入住配置表
            insertCheckInAndCheckInConfig(dto, elder, bed);
            //6.新增合同表
            insertContract(dto, elder);
        }


    }

    private void insertContract(CheckInApplyDto dto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        contract.setStartDate(startDate);
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setEndDate(endDate);
        if (endDate.isBefore(LocalDateTime.now())) {
            //结束时间在当前时间之前,代表合同无效
            contract.setStatus(3L);
        } else {
            //结束时间在当前时间之后,代表合同有效或未开始
            if (startDate.isAfter(LocalDateTime.now())) {
                //开始时间在当前时间之后,代表合同未开始
                contract.setStatus(2L);
            } else {
                //开始时间在当前时间之前,代表合同已开始
                contract.setStatus(1L);
            }
        }
        contract.setSortOrder(1);

        //6.1 插入合同表
        contractMapper.insertContract(contract);
    }

    private void insertCheckInAndCheckInConfig(CheckInApplyDto dto, Elder elder, Bed bed) {
        CheckIn checkIn = CheckIn.builder()
                .elderName(elder.getName())
                .elderId(elder.getId())
                .idCardNo(elder.getIdCardNo())
                .startDate(dto.getCheckInConfigDto().getStartDate())
                .endDate(dto.getCheckInConfigDto().getEndDate())
                .nursingLevelName(dto.getCheckInConfigDto().getNursingLevelName())
                .bedNumber(bed.getBedNumber())
                .status(0)
                .sortOrder(1)
                .build();
        //5.1插入入住表
        checkInMapper.insertCheckIn(checkIn);

        //5.2构建入住配置表
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setSortOrder(1);
        checkInConfigMapper.insertCheckInConfig(checkInConfig);
    }

    private Elder insertelder(CheckInApplyDto dto, Bed bed) {
        Elder elder = new Elder();
        //4.1属性拷贝
        BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
        //4.2 sex属性不一致
        elder.setSex(Long.valueOf(dto.getCheckInElderDto().getSex()));
        //4.3 设置其他字段
        elder.setStatus(1L);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        //4.4 设置老人家属信息
        elder.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        //4.5新增老人数据
        elderMapper.insertElder(elder);
        //4.6新增后,将老人的id设置进去
        elder.setId(elder.getId());
        return elder;
    }

    @Override
    public CheckInDetailVo detail(Integer id) {

        //1.响应老人相关信息
        //1.1根据checkIn id 查找老人身份证号
        CheckIn checkIn = checkInMapper.selectById(id);
        //1.2根据老人身份证号查询老人信息
        LambdaQueryWrapper<Elder> queryWrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkIn.getIdCardNo());
        Elder elder = elderMapper.selectOne(queryWrapper);
        //属性拷贝
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        //性别字段类型不一致
        checkInElderVo.setSex((Integer) (elder.getSex().intValue()));
        //2.封装老人家属信息
        //2.1获取老人家属字符串
        String familyStr = elder.getRemark();
        //2.2将字符串转为json字符串
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(familyStr, ElderFamilyVo.class);
        //3.响应入住配置信息
        //3.1根据id查询入住配置信息
        LambdaQueryWrapper<CheckInConfig> eq = Wrappers.<CheckInConfig>lambdaQuery()
                .eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(eq);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        //4.响应签约办理信息
        LambdaQueryWrapper<Contract> wrapper = Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, elder.getId());
        Contract contract = contractMapper.selectOne(wrapper);
        //5.构建响应对象
        CheckInDetailVo checkInDetailVo = CheckInDetailVo.builder()
                .checkInElderVo(checkInElderVo)
                .checkInConfigVo(checkInConfigVo)
                .elderFamilyVoList(elderFamilyVoList)
                .contract(contract)
                .build();
        return checkInDetailVo;
    }
}
